using MediatR;
using ProduceBasicData.Api.Application.Command.WarehouseManage;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.WarehouseManage
{
    /// <summary>
    /// 删除出库单处理器
    /// </summary>
    public class DeleteStockOutOrderHandler : IRequestHandler<DeleteStockOutOrderCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<StockOutOrder> _stockOutOrderRepository;
        private readonly IBaseRespository<StockOutOrderItem> _stockOutOrderItemRepository;
        private readonly MyDBContext _myDBContext;

        public DeleteStockOutOrderHandler(
            IBaseRespository<StockOutOrder> stockOutOrderRepository,
            IBaseRespository<StockOutOrderItem> stockOutOrderItemRepository,
        MyDBContext myDBContext)
        {
            _stockOutOrderRepository = stockOutOrderRepository;
            _stockOutOrderItemRepository = stockOutOrderItemRepository;
            _myDBContext = myDBContext;
        }

        /// <summary>
        /// 处理删除出库单请求
        /// </summary>
        /// <param name="request">删除出库单命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(DeleteStockOutOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取出库单信息
                var stockOutOrder = await _stockOutOrderRepository.GetModelAsync(request.Id);
                if (stockOutOrder == null)
                {
                    return new ApiResult<int>
                    {
                        Msg = "未找到指定的出库单",
                        Code = ApiEnum.Failed
                    };
                }

                // 创建事务
                using var transaction = await _myDBContext.Database.BeginTransactionAsync(cancellationToken);
                try
                {
                    // 软删除出库单
                    stockOutOrder.Isdel = true;
                    await _stockOutOrderRepository.Update(stockOutOrder);

                    // 软删除出库单明细
                    var items = await _stockOutOrderItemRepository.GetAllAsync(i => i.StockOutOrderId == request.Id && !i.Isdel);
                    if (items != null && items.Any())
                    {
                        foreach (var item in items)
                        {
                            item.Isdel = true;
                            await _stockOutOrderItemRepository.Update(item);
                        }
                    }

                    await _myDBContext.SaveChangesAsync(cancellationToken);

                    // 提交事务
                    await transaction.CommitAsync(cancellationToken);


                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Success,
                        Msg = "删除成功",
                        Data = stockOutOrder.Id
                    };
                }
                catch (Exception)
                {
                    // 回滚事务
                    await transaction.RollbackAsync(cancellationToken);
                    throw;
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"删除出库单时发生错误: {ex.Message}"
                };
            }
        }
    }
}